package org.halk.request;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.zhuhao.utils.httpclient.SpringHttpClientUtils;
import okhttp3.*;
import org.junit.Test;
import org.springframework.http.HttpMethod;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 本地大模型api调用
 *
 * @Author haozhu7
 * @Date 2025/7/22 15:25
 **/
public class LLMLocalServerApi {


    public static final String url = "http://localhost:1234/v1/chat/completions";
    //    public static final String token = "Bearer 643db2f9-1369-40d0-99a8-ade7158870b1";
    String resBodyStr = "";

    /**
     * 获取请求结果
     */
    @Test
    public void getResBody() {
        //读取配置文件中的传参
        URL paramUrl = this.getClass().getClassLoader().getResource("testFile/llmParam.json");
        List<String> strings = FileUtil.readLines(paramUrl, "utf-8");
        String str = String.join("", strings);

        //请求头
        HashMap<String, String> headMap = new HashMap<>();
//        headMap.put("Authorization", token);

        //发送请求获取body
        resBodyStr = SpringHttpClientUtils.requestForObject(url, HttpMethod.POST, String.class, headMap, str);

        System.out.println(resBodyStr);

//        resBodyStr = OkHttpUtil.postJsonParams(url, str, headMap);

//        resBodyStr = HttpRequest
//                .post(url)
//                .contentType("application/json")
//                .body(str)
//                .addHeaders(headMap)
//                .execute()
//                .body();
    }

    @Test
    public void streamApi() throws IOException {

        OkHttpClient client = new OkHttpClient();

        URL paramUrl = this.getClass().getClassLoader().getResource("testFile/llmParam.json");
        List<String> strings = FileUtil.readLines(paramUrl, "utf-8");
        String str = String.join("", strings);

        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("application/json"), str))
                // 根据API要求添加必要的头部
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                // 处理每一行数据，比如打印出来
                String res = line;
                if (res.length() >= 7) {
                    String substring = res.substring(6);
                    if (JSONUtil.isJson(substring)) {
                        JSON json = JSONUtil.parse(substring);
                        List<String> deltaList = (List<String>) JSONUtil.getByPath(json, "choices.delta.content");
                        deltaList = deltaList.stream().filter(Objects::nonNull).collect(Collectors.toList());
                        if (!CollectionUtil.isEmpty(deltaList)) {
                            deltaList.forEach(System.out::println);
                        }
                    }
                } else {
//                    System.out.println(line);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
